package com.cyk.fillter;

import com.cyk.config.UrlConfig;
import com.cyk.feigh.UserFeighClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class PowerUrlFilter implements GlobalFilter, Ordered {

    @Autowired
    private UserFeighClient userFeighClient;

    @Override

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> collect =
                UrlConfig.getInstance().getNeedPowerUrl().stream().filter(t -> request.getPath().toString().indexOf(t) > -1).collect(Collectors.toList());

        if (collect.size() > 0) {
            HttpCookie cookie = request.getCookies().getFirst("token");

            if (cookie == null || userFeighClient.info(cookie.getValue()).isEmpty()) {
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
                response.getHeaders().add("content-type", "text/html;charset=UTF-8");
                DataBuffer wrap = response.bufferFactory().wrap("没有权限".getBytes());
                return response.writeWith(Mono.just(wrap));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
